// pages/task/task.js
const config = require('../../config/api.js');
// const m = require('../../config/Math.js');
// const Big = require('../../config/big.js');
var date = new Date();
var currentHours = date.getHours();
var currentMinute = date.getMinutes();
Page({
  data: {
    categoryArr: [],
    sexArr: ['女', '男', '不限'],
    categoryIndex: 0,
    categoryOrder: '请选择种类',
    sexOrder: '请选择性别',
    changeCateColor: true,
    changeTimeColor: true,
    changeBuildingColor: true,
    changeSexColor: true,
    multiArray: [
      ['今天', '明天', '3-2', '3-3', '3-4', '3-5'],
      [0, 1, 2, 3, 4, 5, 6],
      [0, 10, 20]
    ],
    multiIndex: [0, 0, 0],
    startDate: "请选择日期",
    buildingArr: [],
    buildingOrder: '请选择地点',
    buildingIndex: 0,
    priceArr: [],
    priceAll: 0,
    categoryPrice: 0,
    customPrice: '',
    pickUp: '', //取件信息
    buildingAdreess: '', //选择地点
    buildingId: 0,
    categoryId: 0,
    address: '', //详细地址
    recipient: '', //收件人
    tel: '', //联系方式
    categoryInput: '', //任务种类
    dateInput: '', //选择时间
    taskDesc: '', //任务描述
    taskCode: '', //取件码
    point: '',
    oldmoney: '',
    original_price: '',
    totalPoint: 0,
    sexInput: '',
    sexVal: ''
  },
  onLoad: function() {
    // let buildingUrl = config.buildingUrl;
    // let priceUrl = config.priceUrl;
    // this.http(buildingUrl, this.buildingCallBack)
    // this.http(priceUrl, this.priceCallBack);

  },
  onShow: function() {
    let that = this;
    that.setData({
      categoryOrder: '请选择种类',
      startDate: "请选择日期",
      pickUp: '',
      buildingAdreess: '',
      address: '',
      recipient: '',
      tel: '',
      categoryInput: '',
      dateInput: '',
      taskDesc: '',
      taskCode: '',
      priceAll: 0,
      buildingOrder: '请选择地点',
      changeBuildingColor: true,
      changeCateColor: true,
      oldmoney: '',
      changeTimeColor: true,
    });
    let buildingUrl = config.buildingUrl;
    let priceUrl = config.priceUrl;
    that.http(buildingUrl, that.buildingCallBack)
    that.http(priceUrl, that.priceCallBack);
    wx.request({
      url: config.userInfo,
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        that.setData({
          certStatus: res.data.status,
          totalPoint: res.data.point //当前我所有的积分
        })
      }
    })
    wx.request({
      url: config.integralUrl,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        that.setData({
          point: res.data.per_rmb_point //每次扣除的积分
        })
      }
    })
    wx.request({
        url: config.placeholderUrl,
        method: 'GET',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          // console.log(res)
          that.setData({
            taskPlaceholder: res.data.desc,
            moneyPlaceholder: res.data.money
          })
        }
      }),
      //获取地址
      wx.request({
        url: config.getAddress,
        method: 'GET',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          res.data.forEach((val, index) => {
            if (val.status == '1') {
              that.setData({
                recipient: val.name,
                tel: val.tel,
                address: val.send_address,
                buildingOrder: val.building,
                buildingId: val.building_id,
                isDefault: val.status,
                changeBuildingColor: false
              })
            }
          })
        }
      })
  },

  //发起网络请求函数
  http: function(url, callback) {
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: result => {
        // console.log(result)
        callback(result.data);
      }
    })
  },

  //获取楼层回调函数
  buildingCallBack: function(res) {
    var buildingArr = [];
    var buildingIdArr = [];
    res.forEach((val, index) => {
      buildingArr.push(res[index].address_name);
      buildingIdArr.push(res[index].id);
    })
    this.setData({
      buildingArr: buildingArr,
      buildingIdArr: buildingIdArr
    })
  },

  //获取价格配置回调函数
  priceCallBack: function(res) {
    var categoryArr = [];
    var priceArr = [];
    var categoryIdArr = [];
    res.forEach((val, index) => {
      categoryArr.push(res[index].task_name);
      priceArr.push(res[index].task_price);
      categoryIdArr.push(res[index].id)
    })
    this.setData({
      categoryArr: categoryArr,
      priceArr: priceArr,
      categoryIdArr: categoryIdArr
    })
  },


  //性别选择
  sexChange: function(e) {
    // console.log(e)
    let index = e.detail.value;
    this.setData({
      sexOrder: this.data.sexArr[index],
      sexInput: this.data.sexArr[index],
      changeSexColor: false,
      sexVal: index
    })
  },

  //楼层选择
  bindBuildingChange: function(e) {
    var index = e.detail.value;
    this.setData({
      buildingOrder: this.data.buildingArr[index],
      buildingIndex: index,
      changeBuildingColor: false,
      buildingAdreess: this.data.buildingArr[index],
      buildingId: this.data.buildingIdArr[index]
    })
  },

  //任务种类选择的价格配置
  bindPickerChange: function(e) {
    if (this.data.customPrice == '') {
      this.setData({
        oldmoney: ''
      })
    }
    var index = e.detail.value;
    this.setData({
      categoryOrder: this.data.categoryArr[index],
      categoryIndex: index,
      changeCateColor: false,
      categoryPrice: parseInt(this.data.priceArr[index]),
      categoryInput: this.data.categoryArr[index],
      categoryId: this.data.categoryIdArr[index]
    });
    var customPrice = this.data.customPrice;
    var perPoint = parseInt(this.data.point);
    if (this.data.totalPoint < perPoint) {
      this.setData({
        priceAll: (customPrice + this.data.categoryPrice) / 100,
        priceAllOther: (customPrice + this.data.categoryPrice) / 100,
        original_price: customPrice + this.data.categoryPrice
      })
    } else {
      if (this.data.categoryPrice < 100) {
        this.setData({
          priceAll: (customPrice + this.data.categoryPrice) / 100,
          priceAllOther: (customPrice + this.data.categoryPrice) / 100,
          original_price: customPrice + this.data.categoryPrice
        })
      } else {
        this.setData({
          priceAll: (customPrice + this.data.categoryPrice) / 100 - (this.data.point / 100),
          priceAllOther: (customPrice + this.data.categoryPrice) / 100 - (this.data.point / 100),
          original_price: customPrice + this.data.categoryPrice
        })
      }
    }

  },

  //发布任务
  releaseTask: function() {
    let that = this;
    let pickUp = that.data.pickUp;
    let buildingAdreess = that.data.buildingAdreess;
    let address = that.data.address;
    let recipient = that.data.recipient;
    let tel = that.data.tel;
    let categoryInput = that.data.categoryInput;
    let sexInput = that.data.sexInput;
    let dateInput = that.data.dateInput;
    let taskDesc = that.data.taskDesc;
    let taskCode = that.data.taskCode;
    let certStatus = that.data.certStatus;
    let sexVal = that.data.sexVal;
    let original_price = that.data.original_price;

    if (that.data.isDefault == '1') {
      buildingAdreess = that.data.buildingOrder
    }
    // if (certStatus != 2) {
    //   wx.showModal({
    //     title: '审核状态',
    //     content: '抱歉，您未审核或审核未通过',
    //     confirmText: '前往认证',
    //     success: (res) => {
    //       if (res.confirm) {
    //         wx.navigateTo({
    //           url: '/pages/certification/certification',
    //         })
    //       }
    //     }
    //   })
    // } else 
    if (pickUp == '') {
      wx.showToast({
        title: '请填写取件信息',
        icon: 'none'
      })
    } else if (buildingAdreess == '') {
      wx.showToast({
        title: '请选择送件地点',
        icon: 'none'
      })
    } else if (address == '') {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
    } else if (recipient == '') {
      wx.showToast({
        title: '请填写收件人',
        icon: 'none'
      })
    } else if (tel == '') {
      wx.showToast({
        title: '请填写联系方式',
        icon: 'none'
      })
    } else if (categoryInput == '') {
      wx.showToast({
        title: '请选择任务种类',
        icon: 'none'
      })
    } else if (sexInput == '') {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
    } else if (dateInput == '') {
      wx.showToast({
        title: '请选择送达时间',
        icon: 'none'
      })
    } else if (taskDesc == '') {
      wx.showToast({
        title: '请填写任务描述',
        icon: 'none'
      })
    // } else if (original_price <= 140) {
    //   wx.showToast({
    //     title: '任务金额须大于1.4元',
    //     icon:'none'
    //   })
    } else {
      //发布任务
      wx.request({
        url: config.relTaskUrl,
        method: 'POST',
        data: {
          pick_address: that.data.pickUp,
          building_id: that.data.buildingId,
          send_address: that.data.address,
          name: that.data.recipient,
          tel: that.data.tel,
          task_type_id: that.data.categoryId,
          desc: that.data.taskDesc,
          // goods_code: that.data.taskCode,
          price: (that.data.priceAll) * 100,
          task_time: that.data.dateInput,
          point: parseInt(that.data.totalPoint) < parseInt(that.data.point) ? 0 : parseInt(that.data.point),
          original_price: that.data.original_price,
          sex: parseInt(sexVal)
        },
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token'),
          APPID: 28
        },
        success: function(res) {
          console.log(res)
          that.setData({
            successId: res.data.id,
            categoryOrder: '请选择种类',
            startDate: "请选择日期",
            pickUp: '',
            categoryOrder: '请选择种类',
            categoryInput: '',
            sexOrder: '请选择性别',
            sexInput: '',
            sexVal: '',
            taskDesc: '',
            priceAll: 0,
            customPrice: 0,
            dateInput: '',
            startDate: "请选择日期",
            changeCateColor: true,
            changeTimeColor: true,
            changeSexColor: true,
          });
          // 生成订单号
          wx.request({
            url: config.orderUrl,
            method: 'POST',
            data: {
              title: `送至${that.data.address}`,
              fee: (that.data.priceAllOther) * 100,
              task_id: that.data.successId
            },
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token'),
              APPID: 28
            },
            success: function(res) {
              that.setData({
                orderId: res.data
              })
              //支付
              wx.request({
                url: 'https://api.mokyun.com/wechat/paytest',
                method: 'POST',
                data: {
                  "tradeNo": that.data.orderId
                },
                header: {
                  'Authorization': 'Bearer ' + wx.getStorageSync('token'),
                  'APPID': 28
                },
                success: function(res) {
                  wx.requestPayment({
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: res.data.signType,
                    paySign: res.data.paySign,
                    success: function(res) {
                      wx.request({
                        url: config.orderStatus,
                        method: 'POST',
                        data: {
                          task_id: that.data.successId
                        },
                        header: {
                          'Authorization': 'Bearer ' + wx.getStorageSync('token'),
                          'APPID': 28
                        },
                        success: function(res) {
                          wx.showToast({
                            title: '支付成功',
                            icon: 'none',
                            duration: 1500,
                            success: function() {
                              wx.reLaunch({
                                url: '../index/index',
                              })
                            }
                          })
                        }
                      })
                    },
                    fail: function() {
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none',
                        duration: 1500,
                        success: function() {
                          wx.navigateTo({
                            url: 'published/published'
                          })
                        }
                      })
                    }
                  })
                }
              })
            }
          })
        }
      })
    }
  },

  // 判断各项数据是否为空
  pickInput: function(e) {
    this.setData({
      pickUp: e.detail.value
    })
  },
  addressInput: function(e) {
    this.setData({
      address: e.detail.value
    })
  },
  recipientInput: function(e) {
    this.setData({
      recipient: e.detail.value
    })
  },
  telInput: function(e) {
    this.setData({
      tel: e.detail.value
    })
  },
  taskDescInput: function(e) {
    this.setData({
      taskDesc: e.detail.value
    })
  },
  taskCodeInput: function(e) {
    this.setData({
      taskCode: e.detail.value
    })
  },

  //自定义任务价格
  customPrice: function(e) {
    // console.log(e)
    let categroyInput = this.data.categoryInput;
    let value = parseFloat(e.detail.value);
    let categoryPrice = this.data.categoryPrice;
    if (categroyInput == '') {
      wx.showToast({
        title: '请先选择种类',
        icon: 'none',
        duration: 2000
      })
    } else {
      //isNaN是数字返回false
      if (!isNaN(value)) {
        this.setData({
          customPrice: value * 100,
        })
      } else {
        this.setData({
          customPrice: 0
        })
      }
      var perPoint = this.data.point;
      //如果总积分小于积分抵扣的配置，直接设置总价为任务种类价格+任务金额
      if (this.data.totalPoint < perPoint) {
        this.setData({
          priceAll: (categoryPrice + this.data.customPrice) / 100,
          priceAllOther: (categoryPrice + this.data.customPrice) / 100,
          original_price: categoryPrice + this.data.customPrice
        })
        console.log(this.data.original_price)
      } else {
        //如果总积分不小于积分抵扣的配置，设置总价为任务种类价格+任务金额
        if (this.data.customPrice == 0) {
          this.setData({
            priceAll: 0
          })
        } else {
          if (categoryPrice + this.data.customPrice > 0 && this.data.customPrice + categoryPrice <= 140) {
            this.setData({
              priceAll: (categoryPrice + this.data.customPrice) / 100,
              original_price: categoryPrice + this.data.customPrice
            })
            console.log(this.data.original_price)
          } else {
            var priceAllFormat = (categoryPrice + this.data.customPrice) / 100 - (this.data.point / this.data.point);
            priceAllFormat = m.accSub((categoryPrice + this.data.customPrice) / 100, (this.data.point / this.data.point))
            this.setData({
              // priceAll: (categoryPrice + this.data.customPrice) / 100 - (this.data.point / this.data.point),
              priceAll: priceAllFormat,
              // priceAllOther: (categoryPrice + this.data.customPrice) / 100 - (this.data.point / this.data.point),
              priceAllOther: priceAllFormat,
              original_price: categoryPrice + this.data.customPrice
            })
            console.log(this.data.original_price)
          }
        }
      }
    }
  },


  //送达时间
  pickerTap: function() {
    date = new Date();
    var monthDay = ['今天', '明天'];
    var hours = [];
    var minute = [];
    currentHours = date.getHours();
    currentMinute = date.getMinutes();
    // 月-日
    for (var i = 2; i <= 28; i++) {
      var date1 = new Date(date);
      date1.setDate(date.getDate() + i);
      var md = (date1.getMonth() + 1) + "-" + date1.getDate();
      monthDay.push(md);
    }
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    if (data.multiIndex[0] === 0) {
      if (data.multiIndex[1] === 0) {
        this.loadData(hours, minute);
      } else {
        this.loadMinute(hours, minute);
      }
    } else {
      this.loadHoursMinute(hours, minute);
    }
    data.multiArray[0] = monthDay;
    data.multiArray[1] = hours;
    data.multiArray[2] = minute;
    this.setData(data);
  },

  bindMultiPickerColumnChange: function(e) {
    date = new Date();
    var that = this;
    var monthDay = ['今天', '明天'];
    var hours = [];
    var minute = [];
    currentHours = date.getHours();
    currentMinute = date.getMinutes();
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    // 把选择的对应值赋值给 multiIndex
    data.multiIndex[e.detail.column] = e.detail.value;
    // 然后再判断当前改变的是哪一列,如果是第1列改变
    if (e.detail.column === 0) {
      // 如果第一列滚动到第一行
      if (e.detail.value === 0) {
        that.loadData(hours, minute);
      } else {
        that.loadHoursMinute(hours, minute);
      }
      data.multiIndex[1] = 0;
      data.multiIndex[2] = 0;
      // 如果是第2列改变
    } else if (e.detail.column === 1) {
      // 如果第一列为今天
      if (data.multiIndex[0] === 0) {
        if (e.detail.value === 0) {
          that.loadData(hours, minute);
        } else {
          that.loadMinute(hours, minute);
        }
        // 第一列不为今天
      } else {
        that.loadHoursMinute(hours, minute);
      }
      data.multiIndex[2] = 0;
      // 如果是第3列改变
    } else {
      // 如果第一列为'今天'
      if (data.multiIndex[0] === 0) {
        // 如果第一列为 '今天'并且第二列为当前时间
        if (data.multiIndex[1] === 0) {
          that.loadData(hours, minute);
        } else {
          that.loadMinute(hours, minute);
        }
      } else {
        that.loadHoursMinute(hours, minute);
      }
    }
    data.multiArray[1] = hours;
    data.multiArray[2] = minute;
    this.setData(data);
  },
  loadData: function(hours, minute) {
    var minuteIndex;
    if (currentMinute > 0 && currentMinute <= 10) {
      minuteIndex = 10;
    } else if (currentMinute > 10 && currentMinute <= 20) {
      minuteIndex = 20;
    } else if (currentMinute > 20 && currentMinute <= 30) {
      minuteIndex = 30;
    } else if (currentMinute > 30 && currentMinute <= 40) {
      minuteIndex = 40;
    } else if (currentMinute > 40 && currentMinute <= 50) {
      minuteIndex = 50;
    } else {
      minuteIndex = 60;
    }
    if (minuteIndex == 60) {
      // 时
      var h1;
      for (var i = currentHours + 1; i < 24; i++) {
        h1 = i;
        if (i < 10) {
          h1 = '0' + i
        }
        hours.push(h1);
      }
      // 分
      var m1
      for (var i = 0; i < 60; i += 10) {
        m1 = i;
        if (i < 10) {
          m1 = '0' + i
        }
        minute.push(m1);
      }
    } else {
      // 时
      var h2;
      for (var i = currentHours; i < 24; i++) {
        h2 = i;
        if (i < 10) {
          h2 = '0' + i
        }
        hours.push(h2);
      }
      // 分
      var m2;
      for (var i = minuteIndex; i < 60; i += 10) {
        m2 = i;
        if (i < 10) {
          m2 = '0' + i
        }
        minute.push(m2);
      }
    }
  },

  loadHoursMinute: function(hours, minute) {
    // 时
    var h3;
    for (var i = 0; i < 24; i++) {
      h3 = i;
      if (i < 10) {
        h3 = '0' + i
      }
      hours.push(h3);
    }
    // 分
    var m3;
    for (var i = 0; i < 60; i += 10) {
      m3 = i
      if (i < 10) {
        m3 = '0' + i
      }
      minute.push(m3);
    }
  },

  loadMinute: function(hours, minute) {
    var minuteIndex;
    if (currentMinute > 0 && currentMinute <= 10) {
      minuteIndex = 10;
    } else if (currentMinute > 10 && currentMinute <= 20) {
      minuteIndex = 20;
    } else if (currentMinute > 20 && currentMinute <= 30) {
      minuteIndex = 30;
    } else if (currentMinute > 30 && currentMinute <= 40) {
      minuteIndex = 40;
    } else if (currentMinute > 40 && currentMinute <= 50) {
      minuteIndex = 50;
    } else {
      minuteIndex = 60;
    }
    if (minuteIndex == 60) {
      // 时
      var h4;
      for (var i = currentHours + 1; i < 24; i++) {
        h4 = i;
        if (i < 10) {
          h4 = '0' + i
        }
        hours.push(h4);
      }
    } else {
      // 时
      var h5;
      for (var i = currentHours; i < 24; i++) {
        h5 = i;
        if (i < 10) {
          h5 = '0' + i
        }
        hours.push(h5);
      }
    }
    // 分
    var m4;
    for (var i = 0; i < 60; i += 10) {
      m4 = i;
      if (i < 10) {
        m4 = '0' + i
      }
      minute.push(m4);
    }
  },

  bindStartMultiPickerChange: function(e) {
    var that = this;
    var monthDay = that.data.multiArray[0][e.detail.value[0]];
    var hours = that.data.multiArray[1][e.detail.value[1]];
    var minute = that.data.multiArray[2][e.detail.value[2]];
    if (monthDay === "今天") {
      var month = date.getMonth() + 1;
      var day = date.getDate();
      monthDay = month + "-" + day;
    } else if (monthDay === "明天") {
      var date1 = new Date(date);
      date1.setDate(date.getDate() + 1);
      monthDay = (date1.getMonth() + 1) + "-" + date1.getDate();
    } else {
      var month = monthDay.split("-")[0]; // 返回月
      var day = monthDay.split("-")[1]; // 返回日
      monthDay = month + "-" + day;
    }
    var startDate = monthDay + " " + hours + ":" + minute;
    that.setData({
      startDate: startDate,
      changeTimeColor: false,

    })
    let formatTime = that.formatTime(that.data.startDate);
    that.setData({
      dateInput: formatTime
    })
  },
  formatTime: function(time) {
    let formatTime;
    let year = new Date().getFullYear();
    let md = time.split(' ')[0];
    let sf = time.split(' ')[1];
    let mdFormatMonth = md.split('-')[0];
    let mdFormatDay = md.split('-')[1];
    let sfFormatHour = sf.split(':')[0]
    let sfFormatMinute = sf.split(':')[1]
    if (mdFormatMonth < 10) {
      mdFormatMonth = '0' + mdFormatMonth
    }
    if (mdFormatDay < 10) {
      mdFormatDay = "0" + mdFormatDay
    }
    return formatTime = `${year}-${mdFormatMonth}-${mdFormatDay}` + ' ' + `${sfFormatHour}:${sfFormatMinute}:00`
  }
})